<template>
  <div class="mod-seckill-shopAuditing">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="searchForm"
        :class="$t('language') === 'language' ? 'en-search-form': 'zh-search-form'"
      >
        <div class="input-row">
          <el-form-item
            prop="merchantName"
            label="企业名称:"
          >
            <el-input
              v-model="searchForm.merchantName"
              clearable
              placeholder="企业名称"
            />
          </el-form-item>

          <el-form-item
            prop="createdBy"
            label="申请人:"
          >
            <el-input
              v-model="searchForm.createdBy"
              clearable
              placeholder="申请人"
            />
          </el-form-item>

          <el-form-item
            prop="userMobile"
            label="手机号:"
          >
            <el-input
              v-model="searchForm.userMobile"
              clearable
              maxlength="11"
              placeholder="手机号"
            />
          </el-form-item>

          <el-form-item
            prop="mallVersion"
            label="全网推版本:"
          >
            <el-select
              v-model="searchForm.mallVersion"
              clearable
              placeholder="全网推版本"
            >
              <el-option
                v-for="(item, index) in recVer"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            prop="tradeVersion"
            label="全网买版本:"
          >
            <el-select
              v-model="searchForm.tradeVersion"
              clearable
              placeholder="全网买版本"
            >
              <el-option
                v-for="(item, index) in buyVer"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            prop="auditStatus"
            label="审核状态:"
          >
            <el-select
              v-model="searchForm.auditStatus"
              clearable
              placeholder="审核状态"
            >
              <el-option
                v-for="item in auditStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            prop="auditResult"
            label="审核结果:"
          >
            <el-select
              v-model="searchForm.auditResult"
              clearable
              :placeholder="$t('publics.status')"
            >
              <el-option
                v-for="item in auditResultList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            :label="$t('order.applicationTime') + ':'"
          >
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              :range-separator="$t('date.tip')"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
            />
          </el-form-item>

          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('product.search') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch()"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div class="table-con audit-shop-table">
        <el-table
          :key="tabValue"
          ref="auditShopRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
        >
          <el-table-column
            prop="merchantName"
            label="企业名称"
            width="150"
          />

          <el-table-column
            prop="createdBy"
            label="申请人"
            width="100"
          />

          <el-table-column
            prop="userMobile"
            label="手机号"
            width="120"
          />

          <el-table-column
            prop="mallVersion"
            label="全网推版本"
            width="100"
          >
            <template #default="scope">
              <span class="tag-text">
                {{ recVer.find(d => d.value == scope.row.mallVersion)?.label }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            prop="tradeVersion"
            label="全网买版本"
            width="100"
          >
            <template #default="scope">
              <span class="tag-text">
                {{ buyVer.find(d => d.value == scope.row.tradeVersion)?.label }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            prop="createdTime"
            :label="$t('order.applicationTime')"
            width="200"
          />

          <el-table-column
            width="120"
            label="审核状态"
          >
            <template #default="scope">
              {{ auditStatusList.find(d => d.value == scope.row.auditStatus)?.label || '--' }}
            </template>
          </el-table-column>

          <el-table-column
            width="120"
            label="审核结果"
          >
            <template #default="scope">
              {{ auditResultList.find(d => d.value == scope.row.auditResult)?.label || '--' }}
            </template>
          </el-table-column>

          <el-table-column
            prop="remark"
            label="备注"
          />

          <el-table-column
            align="center"
            fixed="right"
            :label="$t('publics.operating')"
            width="200"
          >
            <template #default="scope">
              <div class="">
                <!-- 查看 -->
                <div
                  class="default-btn text-btn"
                  @click="onView(scope.row.merchantId)"
                >
                  {{ $t('seckill.view') }}
                </div>

                <div
                  v-if="scope.row.auditStatus == 0"
                  class="default-btn text-btn"
                  @click="onApprove(scope.row)"
                >
                  审核
                </div>
                <!-- 编辑 -->
                <div
                  v-if="scope.row.auditStatus == 1"
                  class="default-btn text-btn"
                  @click="onDel(scope.row.id)"
                >
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <!-- 审核 -->
    <el-dialog
      v-model="visible"
      :close-on-click-modal="false"
      title="审核"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        @submit.prevent
      >
        <el-form-item
          label="审核结果"
          prop="auditResult"
        >
          <el-radio-group
            v-model="dataForm.auditResult"
            @change="onChangeResult"
          >
            <el-radio :label="'1'">
              通过
            </el-radio>
            <el-radio :label="'0'">
              不通过
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input
            v-model.trim="dataForm.remark"
            maxlength="100"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t("coupon.cancel") }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="onSubmitApprove()"
          >
            {{ $t("coupon.confirm") }}
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 查看 -->
    <addOrUpdate ref="addOrUpdateRef" />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import addOrUpdate from '../add-or-update/index.vue'
import { recVer, buyVer, buyLev } from '../../constant'

const auditStatusList = reactive([
  {
    label: '未审核',
    value: '0'
  },
  {
    label: '已审核',
    value: '1'
  }
])

const auditResultList = reactive([
  {
    label: '未通过',
    value: '0'
  },
  {
    label: '已通过',
    value: '1'
  }
])

defineProps({
  tabValue: {
    type: String,
    default: ''
  }
})

const searchForm = reactive({})

const visible = ref(false)

const dataForm = ref({
  id: null,
  merchantId: null,
  mallVersion: null,
  tradeVersion: null,
  userMobile: null,
  auditResult: '',
  remark: ''
})

const dataRule = ref({
  auditResult: [
    {
      required: true,
      message: '审核结果不能为空',
      trigger: 'blur'
    }
  ],
  remark: [
    {
      required: false,
      message: '备注不能为空',
      trigger: 'blur'
    }
  ]
})

onMounted(() => {
  getDataList()
})

let tempSearchForm = null // 保存上次点击查询的请求条件
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const dateRange = ref([])
let theParams = null // 保存上次点击查询的请求条件
const dataList = ref([])
const getDataList = (pageParam, newData = false) => {
  pageParam = pageParam || page
  if (newData || !tempSearchForm) {
    tempSearchForm = {
      current: pageParam.currentPage,
      size: pageParam.pageSize,
      beginTime: dateRange.value ? dateRange.value[0] : null, // 开始时间
      endTime: dateRange.value ? dateRange.value[1] : null // 结束时间
    }
    theParams = JSON.parse(JSON.stringify(searchForm))
  } else {
    tempSearchForm.current = pageParam.currentPage
    tempSearchForm.size = pageParam.pageSize
  }

  http({
    url: http.adornUrl('/shop/merchantAudit/page'),
    method: 'get',
    params: http.adornParams(Object.assign(tempSearchForm, theParams))
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    page.currentPage = data.current

    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.currentPage > 1) {
      page.currentPage = 1
      getDataList()
    }
  })
}

// 审核
const dataFormRef = ref(null)
const onApprove = ({ id, merchantId, mallVersion, tradeVersion, userMobile }) => {
  visible.value = true
  dataForm.value.id = id
  dataForm.value.merchantId = merchantId
  dataForm.value.mallVersion = mallVersion
  dataForm.value.tradeVersion = tradeVersion
  dataForm.value.userMobile = userMobile
  dataForm.value.remark = ''
  dataForm.value.auditResult = ''
}

const onChangeResult = (e) => {
  dataRule.value.remark[0].required = e === '0'
}

const onSubmitApprove = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl('/shop/merchantAudit'),
        method: 'put',
        data: http.adornData({
          ...dataForm.value,
          auditStatus: '1'
        })
      }).then(() => {
        visible.value = false
        ElMessage.success('操作成功')
        getDataList(page)
      })
    }
  })
}

const addOrUpdateRef = ref(null)
const onView = (id) => {
  addOrUpdateRef.value?.init(id)
}

const onDel = (id) => {
  ElMessageBox.confirm('确认删除此条记录嘛?', $t('resource.tips'), {
    confirmButtonText: $t('resource.confirm'),
    cancelButtonText: $t('resource.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl(`/shop/merchantAudit/${id}`),
      method: 'delete'
    }).then(() => {
      ElMessage.success('操作成功')
      getDataList(page)
    })
  })
}

// 清空自定义数据
const searchReset = () => {
  dateRange.value = []
}

const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

const auditShopRef = ref(null)
const searchFormRef = ref(null)
/**
 * 重置表单
 */
const onResetSearch = () => {
  searchFormRef.value.resetFields()
  searchReset()
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}
</script>

<style lang="scss" scoped>
.table-con {
  position: relative;
}

:deep(.export-load) {
  top: -50% !important;
}
:deep(.el-table__fixed-right::before) {
  z-index: 0;
}
</style>
